<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class AddPidToCategory extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('category', function (Blueprint $table) {
            $table->unsignedInteger('pid')->default(0)->after('id')->comment('父id');
            $table->index('pid', 'idx_pid');
        });

        // 洗数据
        \App\Kuafu\Category\Model\CategoryModel::query()
                                               ->where('menuId', '!=', 0)
                                               ->get()
                                               ->each(function ($item) {
                                                   $pid = (int)\App\Kuafu\Category\Model\CategoryModel::query()
                                                                                                      ->where('menuId',
                                                                                                          0)
                                                                                                      ->where('name',
                                                                                                          $item->name)
                                                                                                      ->value('id');
                                                   if ($pid) {
                                                       $item->pid = $pid;
                                                       $item->save();
                                                   }
                                               });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('category', function (Blueprint $table) {
            $table->dropColumn('pid');
        });
    }
}
